<?php
class Data_Split
{
    private $dbman;

    public function __construct()
    {
        $this->dbman = new Data_DB();
    }

    function insert($kind, $splitId, $insertField, $updateField = array(), $changeField = array())
    {
        $splitField = $this->splitField($kind);
        if (!isset($insertField[$splitField]))
        {
            $insertField[$splitField] = $splitId;
        }

        $sql = Tool_Sql::insert($kind, $insertField, $updateField, $changeField);
        $this->formatSql($sql, $kind, $splitId);
        return $this->dbman->sQuery($kind, $splitId, $sql);
    }

    function delete($kind, $splitId, $where)
    {
        $splitField = $this->splitField($kind);
        if (is_array($where))
        {
	        if (! isset($where[$splitField]))
	        {
	            $where[$splitField] = $splitId;
	        }
	        $sql = Tool_Sql::delete($kind, $where);
	    }
		elseif (is_string($where))
		{
			if(0 == strlen($where))
	        {
	            return false;
	        }
	        $sql = "delete from ".$kind." where ".$splitField." = '".$splitId."' and ".$where;
		}
		else
		{
			assert(0);
			return false;
		}
		
        if(0 == strlen($sql))
        {
            return false;
        }
        $this->formatSql($sql, $kind, $splitId);
        return $this->dbman->sQuery($kind, $splitId , $sql);
    }

    function update($kind, $splitId, $updateField, $changeField = array(), $whereField = array())
    {
        $splitField = $this->splitField($kind);
        if (!isset($whereField[$splitField]))
        {
            $whereField[$splitField] = $splitId;
        }

        $sql = Tool_Sql::update($kind, $updateField, $changeField, $whereField);
        if(0 == strlen($sql))
        {
            return false;
        }
        $this->formatSql($sql, $kind, $splitId);
        return $this->dbman->sQuery($kind, $splitId , $sql);
    }

    function select($kind, $splitId, $selectField, $where = NULL, $order = "", $start=0, $num=0, $cacheTime=0)
    {
        $splitField = $this->splitField($kind);
        if (is_array($where))
        {
	        if (!isset($where[$splitField]))
	        {
	            $where[$splitField] = $splitId;
	        }
	    }
	    elseif (is_string($where))
	    {
	    	$where .= ($where == "") ? "":" and ";
        	$where .= $splitField . "='" . mysql_escape_string($splitId) . "'";
	    }

        $sql = Tool_Sql::select($kind, $selectField, $where, $order, $start, $num);
        $this->formatSql($sql, $kind, $splitId);
        return $this->dbman->sQuery($kind, $splitId , $sql, $cacheTime);
    }

    private function splitField($kind)
    {
        $key = explode("_", $kind);
        $key = $key[1];
        return Data_Split_Conf::$kind_prefix[$key];
    }

    private function formatSql(&$sql, $kind, $splitId)
    {
        $tableNo = $splitId % DB_SPLIT_NUM;
        $tableName = $kind . '_' . $tableNo;

        $sql = str_replace($kind, $tableName, $sql);
    }
}
?>